import java.util.Stack;

public class Solution1209 {

    static class Pair{
        char ch;
        int num;
        public Pair(char ch, int num) {
            this.ch = ch;
            this.num = num;
        }
    }

    public String removeDuplicates(String s, int k) {
        Stack<Pair> stack=new Stack<>();
        for (char c : s.toCharArray()) {
            if (stack.isEmpty() || c!=stack.peek().ch){
                stack.push(new Pair(c,1));
            }else {
                Pair pair=stack.pop();
                pair.num++;
                if (pair.num<k){
                    stack.push(pair);
                }
            }
        }
        StringBuilder stringBuilder=new StringBuilder();
        while (!stack.isEmpty()){
            Pair pair=stack.pop();
            for (int i=0;i<pair.num;i++){
                stringBuilder.append(pair.ch);
            }
        }
        return stringBuilder.reverse().toString();
    }

    public static void main(String[] args) {
        System.out.println(new Solution1209().removeDuplicates("deeedbbcccbdaa",3));
    }
}
